package com.example.ai.mcp;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.spec.McpSchema;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.mcp.customizer.McpSyncClientCustomizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.List;

@Slf4j
@Component
public class MyMcpSyncClientCustomizer implements McpSyncClientCustomizer {
    @Autowired
    ObjectMapper mapper;
    @Override
    public void customize(String name, McpClient.SyncSpec spec) {
        // Customize the request timeout configuration
        spec.requestTimeout(Duration.ofSeconds(30));

        McpSchema.Root root = new McpSchema.Root("file:///E:/study/52learn/gitcode/learn-spring-ai","temp2");
        // Sets the root URIs that this client can access.
        spec.roots(root);

        /*// Sets a custom sampling handler for processing message creation requests.
        spec.sampling((McpSchema.CreateMessageRequest messageRequest) -> {
            // Handle sampling
            McpSchema.CreateMessageResult result = ...
            return result;
        });*/

        // Adds a consumer to be notified when the available tools change, such as tools
        // being added or removed.
        spec.toolsChangeConsumer((List<McpSchema.Tool> tools) -> {
            // Handle tools change
            try {
                log.info("toolsChangeConsumer ... {}",mapper.writeValueAsString(tools));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        });

        // Adds a consumer to be notified when the available resources change, such as resources
        // being added or removed.
        spec.resourcesChangeConsumer((List<McpSchema.Resource> resources) -> {
            // Handle resources change
            log.info("resourcesChangeConsumer ...");
        });

        // Adds a consumer to be notified when the available prompts change, such as prompts
        // being added or removed.
        spec.promptsChangeConsumer((List<McpSchema.Prompt> prompts) -> {
            // Handle prompts change
            log.info("promptsChangeConsumer ...");
        });

        // Adds a consumer to be notified when logging messages are received from the server.
        spec.loggingConsumer((McpSchema.LoggingMessageNotification log2) -> {
            // Handle log messages
            try {
                log.info("loggingConsumer ...{}",mapper.writeValueAsString(log2));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        });
    }
}
